﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Instrument
{
    public class ProductionMeasure
    {
        public delegate void TransChannelNum(params int[] channelNum);
        public delegate void TransThis(Production production);
        private bool measureFlag = false;
        public bool MeasureFlag
        {
            get
            {
                return measureFlag;
            }
            set
            {
                measureFlag = value;
                if(measureFlag == false)
                {
                    Clear();
                }
            }
        }//指示测试是否正在进行中
        public event TransChannelNum ChannelExceptHandler;//通道异常处理事件
        public event TransThis ResultHandler;//测试结果处理事件
        public readonly Production _production;
        public int MeasureUplimit = 5;//测试次数上限
        double ChannelUplimit;//通道上门限
        double ChannelDownlimit;//通道下门限
        double[][] Data;//数据缓存矩阵
        private int RowIndex = 0;//矩阵行索引
        public ProductionMeasure(Production production)
        {
            this._production = production;
            Data = new double[MeasureUplimit][];
        }
        /// <summary>
        /// 填充缓存用矩阵
        /// </summary>
        /// <param name="Row"></param>
        public void Add(double[] Row)//矩阵填充
        {
            if (MeasureFlag == false)
                return;
            if (RowIndex < MeasureUplimit)
            {
                Data[RowIndex] = Row;
                AnalyzeRow(Row);
            }
            else
            {
                ResultHandler?.Invoke(_production);
                MeasureFlag = false;
                return;
            }
            RowIndex++;
        }
        private void AnalyzeRow(double[] SingleRow)//分析单行
        {
            _production.SetResistanceValue(SingleRow);//合格判据写入了产品类，后期当将代码移植到测试类中
            if(_production.ProductionQuality == Quality.Qualified)
            {
                ResultHandler?.Invoke(_production);
                MeasureFlag = false;
            }
        }
        /// <summary>
        /// 清除所有状态，使当前实例返回原始状态
        /// </summary>
        private void Clear()
        {
            RowIndex = 0;
            _production.ProductionQuality = Quality.Unqualified;
            _production.ResistanceValue = null;
            for(int i = 0;i < Data.Length;i++)
            {
                Data[i] = null;
            }
        }
        private void AnlyzeColmns(double[][] Data)//分析列数据
        {
            
            ChannelExceptHandler?.Invoke();
        }
    }
}
